package com.example.springboot.util.file;


import com.example.springboot.bean.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * Created by tang on 2017/12/15.
 */
public class FileUploader {

    private final static Logger logger = LoggerFactory.getLogger(FileUploader.class);

    public static Document upload(MultipartFile multipartFile, String basePath) {
        Document document = new Document();

        try {
            String fileName = multipartFile.getOriginalFilename();
            String storeName = makeFileName(fileName);
            String childFilePath = makePath(basePath);
            //文件保存路径为 基础盘符路径+子文件路径+文件名， 数据库中只保存子文件路径+文件名
            File uploadFile = new File(basePath + childFilePath + File.separator + storeName);

            document.setFileName(fileName);
            document.setStoreName(storeName);
            document.setUploadDir(childFilePath + File.separator + storeName);
            // document.setFileType();
            document.setFileSize(multipartFile.getSize() / 1024 + "kb");
            document.setUploadTime(new Date());

            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("->文件上传失败<-");
            return null;
        }


        return document;
    }


    public static List<Document> multiUpload(List<MultipartFile> multipartFileList) {
        List<Document> documentList = new ArrayList<Document>();


        return documentList;

    }

    /**
     * UUID+原文件名防止同样名称的不同文件
     *
     * @param filename
     * @return
     */
    private static String makeFileName(String filename) {
        return UUID.randomUUID() + "_" + filename;

    }

    /**
     * 为防止一个目录下出现太多文件
     */
    private static String makePath(String basePath) {

        //以uuid命令文件夹

        String childFilePath = File.separator + UUID.randomUUID();
        String dir = basePath + childFilePath;
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }

        return childFilePath;

    }

}
